// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import Utlis from "../Utlis";
import UINode, { UIType } from "./UINode";


const {ccclass, property} = cc._decorator;

@ccclass
export default class UIManager extends cc.Component {

    private static instance: UIManager;
    public static getInstance(): UIManager {
        if (!this.instance) {
            const node = new cc.Node("UIManager");
            cc.find("Canvas").addChild(node);
            this.instance = node.addComponent(UIManager);
        }
        return this.instance;
    }

    private normal:cc.Node;
    private top:cc.Node;
    private dic:Map<string, UINode> = new Map();

    protected onLoad(): void {

        let widget = this.node.addComponent(cc.Widget);
        Utlis.widgetAdapterFullScene(widget);
        this.normal = new cc.Node("Normal");
        widget = this.normal.addComponent(cc.Widget);
        Utlis.widgetAdapterFullScene(widget);
        this.top = new cc.Node("Top");
        widget = this.top.addComponent(cc.Widget);
        Utlis.widgetAdapterFullScene(widget);
        this.node.addChild(this.normal);
        this.node.addChild(this.top);
    }

    //打开界面
    async show<T extends UINode>(className:string):Promise<T> {
        let type = cc.js.getClassByName(className) as any;
        const prefabPath = `prefabs/${className}`;
        const prefab:cc.Prefab = await Utlis.loadPrefab(prefabPath);
        const node:cc.Node = cc.instantiate(prefab);
        const ins:UINode = node.addComponent(type);
        const uiType = ins.uiType();
        if(uiType === UIType.Normal) {
            this.normal.addChild(node);
        } else if(uiType === UIType.Top) {
            this.top.addChild(node);
        }
        this.dic.set(className, ins);
        return ins as T;
    }

    async close(className:string) {
        const ins = this.dic.get(className);
        if(ins) {
            ins.node.destroy();
            this.dic.delete(className);
        }
    }
}


